package fab.tools
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class RectangleSelector extends Sprite
	{
		static public var instance:RectangleSelector;
		static public var container:DisplayObjectContainer;
		static public var selection:Rectangle = new Rectangle();
		static public var start_selection:Function;
		static public var move_selection:Function;
		static public var release_selection:Function;
		static public var shut:Boolean=false;
		static public var ratio:Number;
		private var start_click:Point;
		static public function setup( doc:DisplayObjectContainer, start:Function=null, move:Function=null, release:Function=null ):void
		{
			if ( instance == null ) new RectangleSelector( doc );
			start_selection = start;
			move_selection = move;
			release_selection = release;
		}
		public function RectangleSelector( doc:DisplayObjectContainer )
		{
			container = doc;
			container.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
			instance = this;
		}
		public function mouseDown(event:MouseEvent):void
		{
			if ( shut ) return;
			//if ( !(event.target is Level ) ) return;
			//if ( event.target is Draggable ) return;
			//if ( event.target is UIComponent ) return;
			start_click = new Point( container.mouseX, container.mouseY );
			container.addEventListener(MouseEvent.MOUSE_MOVE, bouge);
			container.addEventListener(MouseEvent.MOUSE_UP, mouseReleased);
			if ( start_selection != null ) start_selection();
		}
		public function mouseReleased(event:MouseEvent):void
		{
			if ( shut ) return;
			if ( container.contains( this ) ) container.removeChild( this );
			container.removeEventListener(MouseEvent.MOUSE_MOVE, bouge);
			container.removeEventListener(MouseEvent.MOUSE_UP, mouseReleased);
			if ( release_selection != null ) release_selection();
		}
		public function bouge(event:MouseEvent):void
		{
			if ( shut ) return;
			if ( !container.contains( this ) ) container.addChild( this );
			var mouse:Point = new Point( container.mouseX, container.mouseY );

			selection.x = Math.min( start_click.x, mouse.x );
			selection.y = Math.min( start_click.y, mouse.y );
			selection.width = Math.abs( mouse.x - start_click.x );
			selection.height = Math.abs( mouse.y - start_click.y );
			if ( ratio > 0 ) selection.height = selection.width / ratio;
			draw_zone();
			if ( move_selection != null ) move_selection();
		}
		public function draw_zone():void
		{
			graphics.clear();
			graphics.lineStyle( 0, 0x222288, .6 );
			graphics.beginFill( 0x222288, .2 );
			graphics.drawRect( selection.x, selection.y, selection.width, selection.height );
			graphics.endFill();
		}		
	}
}